<script setup lang="ts">
import {ref, reactive} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {loginApi} from '@/api/login'
import { useUserStore } from '@/stores/modules/user'

const userStore = useUserStore()
// 获取时刻
function getTimePeriod() {
  const hour = new Date().getHours(); // 获取当前小时 (0-23)
  if (hour >= 5 && hour < 8) {
    return '早上';
  } else if (hour >= 8 && hour < 12) {
    return '上午';
  } else if (hour >= 12 && hour < 14) {
    return '中午';
  } else if (hour >= 14 && hour < 18) {
    return '下午';
  } else if (hour >= 18 && hour < 22) {
    return '晚上';
  } else if (hour >= 22 || hour < 5) {
    return '深夜';
  }
}

const timePeriod = getTimePeriod();


const ruleFormRef = ref<FormInstance>()

interface RuleForm {
  username: string
  password: string
}

// 登录信息
const loginInfo = reactive<RuleForm>({
  username: "",
  password: ""
})


const rules = reactive<FormRules<RuleForm>>({
  username: [{required: true, message: '账号不能为空', trigger: 'blur'}],
  password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
})

// 按钮loading
const loading = ref(false)
// 登录
const signIn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl?.validate(async (isValid: boolean) => {
    if (isValid) {
      loading.value = true
      try {
        const res = await loginApi(loginInfo)
console.log(res)
        if (res) {
          userStore.setUserInfo({
            username: res.data.username,
            password: res.data.password
          })


        }
      } finally {
        loading.value = false
      }
    }
  })
}

</script>

<template>
  <h2>{{ timePeriod }}好,欢迎登录!</h2>
  <el-form
    ref="ruleFormRef"
    label-position="top"
    :model="loginInfo"
    :rules="rules">
    <el-form-item label="账号" prop="username">
      <el-input v-model="loginInfo.username" size="large"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="loginInfo.password" size="large" type="password"/>
    </el-form-item>
    <el-form-item>
      <el-button size="large" type="primary" :loading="loading" @click="signIn(ruleFormRef)">登录
      </el-button>
    </el-form-item>
  </el-form>

</template>

<style scoped lang="less">
h2 {
  margin-bottom: 30px;
}

::v-deep .el-form-item__label {
  color: #ffffff;
}

.el-button--large {
  width: 100%;
  margin-top: 20px;
  background: #2e68ff;
  border-color: #2e68ff;
}
</style>
